<template>
  <a-modal width="90%" v-model:visible="visible" :mask-closable="false" :esc-to-close="false" unmount-on-close @close="onCancel">
    <template v-if="query?.title" #title>{{ query?.title }}</template>
    <div class="car-payment-plan-wrapper">
      <div class="payment-plan-wrapper" ref="costRef">
        <!-- 车辆费用单号 -->
        <!-- feeCategory 0-购置费 6-借调费 5-其他费用
              feeNameId 59-借出  61-借调附加费 58-跨门店借调费 -->
        <div class="car-purchase-code" v-if="(query.feeCategory == 0 || query.feeCategory == 6) && query.feeNameId !== 61">
          <div class="car-info">
            <div class="mr56">
              <span>车辆费用单号：</span>
              <span>{{ query.businesCode }}</span>
            </div>
            <div class="mr56">
              应{{ query.feeNameId == 59 ? '收' : '付' }}总额：
              <span class="num">{{ allAmount?.payableTotalAmount ?? 0 }}</span>
              <span class="ml-1">元</span>
            </div>
            <div class="mr56">
              已{{ query.feeNameId == 59 ? '收' : '付' }}总额：
              <span class="num">{{ allAmount?.paidTotalAmount ?? 0 }}</span>
              <span class="ml-1">元</span>
            </div>
            <div class="mr56">
              剩余应{{ query.feeNameId == 59 ? '收' : '付' }}：
              <span class="num">{{ allAmount?.unpaidTotalAmount ?? 0 }}</span>
              <span class="ml-1">元</span>
            </div>
            <div class="mr56">
              {{ allAmount?.purchaseFeeType == 1 ? '车辆购置费总额' : '车辆借入总额' }}：
              <span class="num">{{ allAmount?.purchaseTotalFee ?? 0 }}</span>
              <span class="ml-1">元</span>
            </div>
          </div>
          <a-button @click="addPaymentPlanFn()" v-if="query.installment == 1" type="primary">添加新分期</a-button>
        </div>
        <div class="add-cost-title" v-if="query.feeCategory == 5 || query.feeNameId == 61">
          其他费用：
          <a-button type="primary" @click="onAddClick">添加</a-button>
        </div>
        <page-form :model="table" ref="formRef" layout="vertical">
          <!-- 其他费用 -->
          <table-index :table="table" v-if="query.feeCategory == 5 || query.feeNameId == 61">
            <template #feeCategory="{ record, rowIndex }">
              <page-form-item
                size="1"
                style="margin-bottom: 0"
                :feild="`dataList[${rowIndex}].costType`"
                :rules="{ required: true, message: '请选择' }"
              >
                <a-select v-model="record.costType" style="width: 100%">
                  <a-option :value="0">收款</a-option>
                  <a-option :value="1">付款</a-option>
                </a-select>
              </page-form-item>
            </template>
            <template #totalAmount="{ record, rowIndex }">
              <page-form-item
                size="1"
                style="margin-bottom: 0"
                :field="`dataList[${rowIndex}].amount`"
                :rules="{ required: true, message: '请输入' }"
              >
                <i-input-number placeholder="请输入" v-model="record.amount" />
              </page-form-item>
            </template>
            <template #remark="{ record }">
              <page-form-item size="1" style="margin-bottom: 0">
                <i-input v-model="record.remark" />
              </page-form-item>
            </template>
          </table-index>
        </page-form>
        <page-form :model="tableAmount" ref="formTableRef" layout="vertical">
          <!-- 0-购置费 6-借调费 -->
          <table-index :table="tableAmount" v-if="(query.feeCategory == 0 || query.feeCategory == 6) && query.feeNameId !== 61">
            <template #payableNumStr="{ record }">
              <div
                >{{ query.feeCategory == 5 || (query.feeCategory == 6 && query.installment == 0) ? '' : allAmount.feeCategoryName + '-'
                }}{{ record.payableNumStr }}</div
              >
            </template>
            <template #payableTimeStr="{ record, rowIndex }">
              <template v-if="record.payableStatus == 'paid' && record.payableNum > 0">{{ record.payableTimeStr }}</template>
              <template v-else>
                <page-form-item
                  size="1"
                  style="margin-bottom: 0"
                  :field="`dataList[${rowIndex}].payableTimeStr`"
                  :rules="{ required: true, message: '请选择' }"
                >
                  <i-date-picker
                    :trigger-props="{ updateAtScroll: true }"
                    v-model="record.payableTimeStr"
                    :disabledDate="(value: any) => disabledDate(value, record)"
                    :disabled="record.payableStatusName == '已付款' && record.payableNum > 0"
                    @change="onDateChange"
                  />
                </page-form-item>
              </template>
            </template>
            <template #payableAmount="{ record, rowIndex }">
              <template v-if="record.payableStatus == 'paid'">{{ record.payableAmount }}</template>
              <template v-else>
                <page-form-item
                  size="1"
                  style="margin-bottom: 0"
                  :field="`dataList[${rowIndex}].payableAmount`"
                  :rules="{ required: true, message: '请输入' }"
                >
                  <i-input-number :min="0.01" v-model="record.payableAmount" unit="" :disabled="record.payableStatusName == '已付款'" />
                </page-form-item>
              </template>
            </template>
            <template #billRemark="{ record }">
              <i-input v-model="record.billRemark" :max-length="10" />
            </template>
            <template #paymentAmount="{ record }">
              {{ record.paymentAmount || '-' }}
            </template>
            <template #payableStatusName="{ record }">
              {{ record.payableStatusName || '-' }}
            </template>
            <template #paymentTime="{ record }">
              {{ record.paymentTime || '-' }}
            </template>
            <template #operate="{ record, rowIndex }">
              <div class="table-operator" v-if="record.payableStatusName !== '已付款' && record.payableStatusName !== '已收款'">
                <div class="operate-item operate-minus" @click="delPaymentPlanFn(rowIndex, record)">
                  <icon-minus-circle style="margin-right: 8px" />删除账期
                </div>
              </div>
            </template>
          </table-index>
        </page-form>
      </div>
      <!-- 编辑付款计划，二次确认 -->
      <car-payment-plan-confirm-modal ref="carPaymentPlanConfirmModalRef" @ok="saveApi" />
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onCancel">关闭</a-button>
        <a-button type="primary" :loading="submitLoading" @click="handleOk">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup name="CarPaymentPlanModal" lang="ts">
  import { ref, computed, watch, nextTick } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { editPurchaseBillInfo, findPayableListById, updateOtherFee, getUpdateOtherFeeDetail } from '@/api/asset/car'
  import { getEditFeeDetailByType2, editFeeDetailForType2 } from '@/api/asset/carTransfer'
  import carPaymentPlanConfirmModal from './components/car-payment-plan-confirm-modal.vue'
  import { useTable } from '@/hooks/table'
  import dayjs from 'dayjs'
  import { addFee } from '@/api/asset/carTransfer'

  const formRef = ref()
  const formTableRef = ref()
  const visible = ref(false)
  const emits = defineEmits(['confirm'])

  // 未分期
  const sourceTit = ref('付')
  const tableAmount = useTable({
    tableHeight: '60vh',
    tableLoading: false,
    pagination: false,
    columns: [
      { title: '期数', dataIndex: 'payableNumStr', slotName: 'payableNumStr', width: 140, fixed: 'left' },
      {
        title: '应结日期',
        dataIndex: 'payableTimeStr',
        slotName: 'payableTimeStr',
        width: 170,
      },
      {
        title: `应${sourceTit.value}金额(元)`,
        dataIndex: 'payableAmount',
        slotName: 'payableAmount',
        width: 120,
      },
      {
        title: `实${sourceTit.value}金额(元)`,
        dataIndex: 'paymentAmount',
        slotName: 'paymentAmount',
        width: 120,
      },
      { title: '费用状态', dataIndex: 'payableStatusName', slotName: 'payableStatusName', width: 100 },
      {
        title: `实际${sourceTit.value}款时间`,
        dataIndex: 'paymentTime',
        slotName: 'paymentTime',
        width: 130,
      },
      { title: '备注', dataIndex: 'billRemark', slotName: 'billRemark', width: 220 },
      {
        title: '操作',
        dataIndex: 'operate',
        slotName: 'operate',
        fixed: 'right',
        width: 135,
      },
    ],
    dataList: [],
  })
  watch(sourceTit, () => {
    tableAmount.columns.forEach((col) => {
      col.title = col.title.replace(/(应|实|完成|实际)(收|付)/, `$1${sourceTit.value}`)
    })
  })
  const table = useTable({
    tableLoading: false,
    pagination: false,
    columns: [
      {
        title: '费用名称',
        dataIndex: 'itemName',
        width: 120,
      },
      {
        title: '收付款类型',
        dataIndex: 'feeCategory',
        slotName: 'feeCategory',
        width: 150,
      },
      {
        title: '金额',
        dataIndex: 'totalAmount',
        slotName: 'totalAmount',
        width: 150,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        slotName: 'remark',
        width: 150,
      },
    ],
    operates: [
      {
        label: '删除',
        type: 'danger',
        method: (record: any, column: any, rowIndex: number) => {
          table.dataList.splice(rowIndex, 1)
        },
      },
    ],
    dataList: [],
  })

  const onAddClick = () => {
    table.dataList.push({
      itemName: '车辆购置补充费',
      costType: 1,
      totalAmount: '',
      remark: '',
    })
  }

  // 删除分期
  const delPaymentPlanFn = (index: number, record: any) => {
    // 判断是否是 payableNum > 0
    if (query.value.installment == 1) {
      const isPayableNumLarge = record.payableNum > 0
      if (isPayableNumLarge) {
        // 找到所有 payableNum > 0 的项
        const payableNumPositiveItems = tableAmount.dataList.filter((item) => item.payableNum > 0)
        // 如果分期部分只剩下一期，不允许删除
        if (payableNumPositiveItems.length == 1) {
          Message.warning(`分期期数不能少于一期`)
          return false
        }
        // 获取分期部分最后一项的索引
        const lastIndex = tableAmount.dataList.lastIndexOf(payableNumPositiveItems[payableNumPositiveItems.length - 1])
        // 如果当前点击的索引不是分期部分的最后一项，提示无法删除
        if (index !== lastIndex) {
          Message.warning('分期部分的账期请从最后一期开始删除')
          return false
        }
      }
    }
    // 符合条件，正常删除
    tableAmount.dataList.splice(index, 1)
    tableAmount.dataList = processAndSetDates(tableAmount.dataList)

    // 增加删除成功提示
    Message.success('删除成功')
  }
  // 添加分期
  const costRef = ref(null)
  const addPaymentPlanFn = () => {
    let tableVal = tableAmount.dataList || []

    // 获取所有 payableNum > 0 的项
    const positiveItems = tableVal.filter((item: { payableNum: number }) => item.payableNum > 0)

    // 找到最后一个 payableNum > 0 的项
    const lastPositiveItem = positiveItems[positiveItems.length - 1]
    const lastIndex = tableVal.findIndex((item: any) => item == lastPositiveItem)

    // 递归查找最近的有效 payableTimeStr
    const findMinDate = (index) => {
      if (index < 0) {
        return new Date(new Date().getFullYear() - 10, 0, 1).getTime() // 如果没有有效值，返回过去10年的时间
      }

      const currentItem = tableVal[index]
      if (currentItem.payableTimeStr) {
        return dayjs(currentItem.payableTimeStr).valueOf()
      }

      return findMinDate(index - 1) // 继续向上查找
    }

    // 设置新分期的 minDate
    const minDate = findMinDate(lastIndex)

    // 新分期的 payableNum 和 payableNumStr
    let payableNum = lastPositiveItem.payableNum + 1
    let payableNumStr = `第${payableNum}期`

    // 创建新分期项
    let payableStatusName = '未付款'
    if (query.value.feeNameId == 59) {
      payableStatusName = '未收款'
    }
    let newTableItem = {
      payableNum,
      payableNumStr: payableNumStr,
      settlementStatusStr: '待结算',
      payableStatusName: payableStatusName,
      contractId: query.value.id,
      minDate: minDate, // 使用计算得出的 minDate
    }
    // 在最后一个 payableNum > 0 的项后面插入新分期
    tableAmount.dataList.splice(lastIndex + 1, 0, newTableItem)
    nextTick(() => {
      const element = costRef.value.querySelector('.arco-scrollbar-container .arco-table-body')
      // 使用 scrollTo 方法实现平滑滚动
      element.scrollTop = 10000
    })
  }
  const onCancel = () => {
    visible.value = false
    submitLoading.value = false
  }

  // 获取分期数
  const getInstalmentNum = (data: any) => {
    return data.filter((item: any) => item.payableNum > 0).length
  }
  //比较价格提取
  const processPayableData = (payableNum: number, name: string, prevData: any[], nowData: any[], amountData: any[]) => {
    if (prevData.some((item: { payableNum: any }) => item.payableNum == payableNum)) {
      const obj = {
        name,
        prev: '',
        now: '',
      }
      const prevIndex = prevData.findIndex((item: { payableNum: any }) => item.payableNum == payableNum)
      obj.prev = prevData[prevIndex].payableAmount

      const nowIndex = nowData.findIndex((item: { payableNum: any }) => item.payableNum == payableNum)
      if (nowIndex !== -1) {
        obj.now = nowData[nowIndex].payableAmount
      } else {
        obj.now = '删除'
      }
      // 检查是否发生变化
      if (obj.prev !== obj.now) {
        amountData.push(obj)
        return true // 表示发生了变化
      }
    }
    return false // 表示没有变化
  }
  const carPaymentPlanConfirmModalRef = ref()
  const renderCompare = () => {
    // 判断必填项是否书写 start
    let nowData = tableAmount.dataList
    let hasNoInput = nowData.some((item: any) => {
      let flag = !item.payableTimeStr || item.payableAmount == '' || item.payableAmount == undefined
      return flag
    })

    if (hasNoInput) {
      return Message.warning('请填写必填项')
    }
    let prevData = prevRecordData.payableList
    let amountData: any = []
    // 变化的数量
    let changedNumber = 0
    // 1 费用是否有变化

    const payableItems = [
      { payableNum: -10, name: '购置税' },
      { payableNum: -11, name: '过户费' },
      { payableNum: -12, name: '运输费' },
      { payableNum: -13, name: '保证金' },
      { payableNum: -14, name: '手续费' },
      { payableNum: -1, name: '首付' },
      { payableNum: -2, name: '尾款' },
    ]
    payableItems.forEach(({ payableNum, name }) => {
      const changed = processPayableData(payableNum, name, prevData, nowData, amountData)
      if (changed) {
        changedNumber += 1
      }
    })
    // 2 账单总金额同车辆详情中设置的合同总金额是否有出入
    let totalAmount = {
      change: false,
      prev: 0,
      now: 0,
    }
    let prevSum = 0
    prevData.forEach((item: any) => {
      prevSum += Number(item.payableAmount)
    })
    let nowSum = 0
    nowData.forEach((item: any) => {
      nowSum += Number(item.payableAmount)
    })
    totalAmount.prev = Number(prevSum.toFixed(2))
    totalAmount.now = Number(nowSum.toFixed(2))
    let changedTotalAmount = prevSum != nowSum
    if (changedTotalAmount) {
      totalAmount.change = changedTotalAmount
      changedNumber += 1
    }
    // 3 期数是否有变化
    let prevInstalmentNum = getInstalmentNum(prevData)
    let nowInstalmentNum = getInstalmentNum(nowData)
    let lnstalmentNum = {
      change: false,
      prev: prevInstalmentNum,
      now: nowInstalmentNum,
    }
    let changedInstalmentNum = prevInstalmentNum != nowInstalmentNum
    if (changedInstalmentNum) {
      lnstalmentNum.change = true
      changedNumber += 1
    }
    if (changedNumber > 0) {
      let confirmData = {
        amountData,
        totalAmount,
        lnstalmentNum,
      }
      carPaymentPlanConfirmModalRef.value.open(confirmData)
    } else {
      saveApi()
    }
  }
  const handleOk = () => {
    //  feeCategory 0-购置费 6-借调费 5-其他费用
    //  feeNameId 59-借出 61-借调附加费 58-跨门店用车借调费
    if (query.value.feeCategory == 5) {
      formRef.value.validate((error: any) => {
        if (!error) {
          updateOtherFee({ carId: query.value.carId, feeId: query.value.id, operateType: 5, feeList: table.dataList }).then((res: any) => {
            Message.success('修改成功')
            visible.value = false
            emits('confirm')
          })
        }
      })
    } else if (query.value.feeCategory == 6) {
      if (query.value.feeNameId == 61 || query.value.feeNameId == 58) {
        formRef.value.validate((error: any) => {
          if (!error) {
            // 借调附加费 61 借调费 58
            let arr = []
            if (query.value.feeNameId == 58) {
              arr = tableAmount.dataList.map((item: { payableAmount: any; billRemark: any; payableTimeStr: any }) => {
                return Object.assign(item, {
                  amount: item.payableAmount,
                  remark: item.billRemark,
                  dueDate: item.payableTimeStr,
                })
              })
            } else {
              arr = table.dataList
            }
            addFee({
              id: query.value.businesId,
              feeList: arr,
              feeId: query.value.id || '', //借调附加费需要
            }).then(() => {
              Message.success('修改成功')
              visible.value = false
              emits('confirm')
            })
          }
        })
      } else {
        formTableRef.value.validate((error: any) => {
          if (!error) {
            if (query.value.installment == 1) {
              renderCompare()
            } else {
              saveApi()
            }
          }
        })
      }
    } else {
      formTableRef.value.validate((error: any) => {
        if (!error) {
          if (query.value.installment == 1) {
            renderCompare()
          }
          if (query.value.installment == 0) {
            saveApi()
          }
        }
      })
    }
  }
  // 保存接口
  const submitLoading = ref(false)
  const saveApi = () => {
    if (query.value.feeNameId == 59) {
      let list = tableAmount.dataList
      let tempList = list.map((item: any) => {
        let payableTime = null
        if (item.payableTimeStr) {
          payableTime = item.payableTimeStr.replace(/\//g, '-') + ' 00:00:00'
        }
        return {
          id: item.id,
          payableNum: item.payableNum,
          payableTime: payableTime,
          payableAmount: item.payableAmount,
          billRemark: item.billRemark,
          contractId: item.contractId,
        }
      })
      editFeeDetailForType2({
        id: query.value.businesId,
        payableList: tempList,
      }).then(() => {
        Message.success('修改成功')
        visible.value = false
        emits('confirm')
      })
    } else {
      let list = tableAmount.dataList
      let tempList = list.map((item: any) => {
        let payableTime = null
        if (item.payableTimeStr) {
          payableTime = item.payableTimeStr.replace(/\//g, '-') + ' 00:00:00'
        }
        return {
          id: item.id,
          payableNum: item.payableNum,
          payableTime: payableTime,
          payableAmount: item.payableAmount,
          billRemark: item.billRemark,
          contractId: item.contractId,
        }
      })
      submitLoading.value = true
      editPurchaseBillInfo({
        id: query.value.businesId,
        payableList: tempList,
      })
        .then(() => {
          Message.success('修改成功')
          submitLoading.value = false
          visible.value = false
          emits('confirm')
        })
        .catch(() => {
          submitLoading.value = false
        })
    }
  }
  const processAndSetDates = (list: any[]) => {
    const defaultMinDate = new Date(new Date().getFullYear() - 10, 0, 1).getTime() // 过去十年
    const defaultMaxDate = new Date(new Date().getFullYear() + 10, 0, 1).getTime() // 未来十年

    // 递归查找上一期有效的 payableTimeStr（仅限 payableNum > 0）
    const findPrevDate = (currentIndex: number): number => {
      if (currentIndex < 0) return defaultMinDate // 返回默认最小日期
      const prevItem = list[currentIndex]
      if (prevItem.payableNum > 0 && prevItem.payableTimeStr) {
        return dayjs(prevItem.payableTimeStr).valueOf()
      }
      return findPrevDate(currentIndex - 1) // 继续向上查找
    }

    // 递归查找下一期有效的 payableTimeStr（仅限 payableNum > 0）
    const findNextDate = (currentIndex: number): number => {
      if (currentIndex >= list.length) return defaultMaxDate // 如果越界，返回默认最大日期
      const nextItem = list[currentIndex]
      if (nextItem.payableNum > 0 && nextItem.payableTimeStr) {
        return dayjs(nextItem.payableTimeStr).valueOf()
      }
      return findNextDate(currentIndex + 1) // 继续向下查找
    }
    if (list.length > 0) {
      // 遍历列表并处理日期范围
      list.forEach((item: any, index: number) => {
        if (item.payableNum == -1) {
          // 找到尾款项
          const tailItem = list.find((record: any) => record.payableNum == -2)
          if (tailItem) {
            tailItem.minDate = item.payableTimeStr ? dayjs(item.payableTimeStr).valueOf() : defaultMinDate
          }
        } else if (item.payableNum == -2) {
          // 找到首付项
          const initialItem = list.find((record: any) => record.payableNum == -1)
          if (initialItem) {
            initialItem.maxDate = item.payableTimeStr ? dayjs(item.payableTimeStr).valueOf() : defaultMaxDate
          }
        } else if (item.payableNum > 0) {
          // 分期部分
          const minDate = findPrevDate(index - 1) // 找到上一期有效日期
          const maxDate = findNextDate(index + 1) // 找到下一期有效日期
          item.minDate = minDate
          item.maxDate = maxDate
        } else {
          // 非分期部分
          item.minDate = null
          item.maxDate = null
        }
      })
    }

    return list || [] // 返回处理后的列表
  }

  const onDateChange = () => {
    tableAmount.dataList = processAndSetDates(tableAmount.dataList)
  }
  const disabledDate = (current: any, record: any) => {
    // 查找 record 在 tableAmount.dataList 中对应的项
    const targetRecord = tableAmount.dataList.find((item: any) => item == record)
    if (!targetRecord) {
      return true // 禁用日期，防止错误
    }
    let minDate = targetRecord.minDate || null
    let maxDate = targetRecord.maxDate || null
    // 将 current 转换为时间戳
    const currentTimestamp = dayjs(current).valueOf()
    return currentTimestamp < dayjs(minDate).valueOf() || currentTimestamp > dayjs(maxDate).valueOf()
  }
  let prevRecordData: any = null
  const query = ref()
  const allAmount: any = ref({})
  const open = (option: { title: string; feeCategory: number; installment: number; id: number; _id: number; feeNameId: number }) => {
    visible.value = true
    query.value = option
    //  feeCategory 0-购置费 6-借调费 5-其他费用
    //  feeNameId 59-借出  61-借调附加费 58-跨门店借调费
    sourceTit.value = option.feeNameId == 59 ? '收' : '付'
    if ((option.feeCategory == 6 || option.feeCategory == 0) && option.feeNameId !== 58) {
      if (option.feeNameId == 59) {
        // 借出
        getEditFeeDetailByType2({ id: option.id }).then((res: any) => {
          const result = res.result
          // 备注数据字段统一
          result.payableList = result.payableList.map((item) => {
            return Object.assign(item, { billRemark: item.remark })
          })
          tableAmount.dataList = processAndSetDates(result.payableList)
          prevRecordData = JSON.parse(JSON.stringify(result))
          allAmount.value = result
        })
      } else {
        // 车辆购置
        findPayableListById({ id: option.id }).then((res: any) => {
          const result = res.result
          tableAmount.dataList = processAndSetDates(result.payableList)
          prevRecordData = JSON.parse(JSON.stringify(result))
          allAmount.value = result
        })
      }
    }
    if (option.feeCategory == 5 || option.feeNameId == 61 || option.feeNameId == 58) {
      // 其他费用 借调附加费  跨门店借调费
      getUpdateOtherFeeDetail({ id: option.id, feeCategory: option.feeCategory }).then((res: any) => {
        if (option.feeNameId == 58) {
          const result = res.result
          allAmount.value = {
            payableTotalAmount: result.totalAmount,
            paidTotalAmount: result.payAmount,
            unpaidTotalAmount: result.surplusAmount,
          }
          tableAmount.dataList = [
            Object.assign(result.feeDetailList[0], {
              payableNumStr: result?.feeDetailList[0]?.itemName || '',
              payableTimeStr: result.dueDate,
              payableAmount: result.totalAmount,
              paymentTime: result.payTime,
              payableStatusName: result.feeStatusName,
              billRemark: result.remark,
            }),
          ]
        } else {
          const result = res.result
          console.log(result.feeDetailList)
          table.dataList = result.feeDetailList || []
        }
      })
    }
  }
  watch(
    () => tableAmount.dataList,
    (newVal) => {
      allAmount.value.payableTotalAmount = newVal.reduce((total, item) => {
        // 确保 item.payableAmount 是数字，若不是则默认使用 0
        const payableAmount = Number(item.payableAmount) || 0
        return total + payableAmount
      }, 0)
      // 保证小数点后两位，避免浮点数精度问题
      allAmount.value.payableTotalAmount = parseFloat(allAmount.value.payableTotalAmount.toFixed(2))
      // 确保计算结果是数字，若是 NaN 或其他非数字，设为 0
      allAmount.value.unpaidTotalAmount =
        parseFloat((Number(allAmount.value.payableTotalAmount) - Number(allAmount.value.paidTotalAmount)).toFixed(2)) || 0
    },
    { immediate: true, deep: true }
  )
  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .car-payment-plan-wrapper {
    width: 100%;
  }
  .add-cost-title {
    margin-bottom: 20px;
  }
  .car-purchase-code {
    margin-bottom: 16px;
    justify-content: space-between;
    display: flex;
    .car-info {
      display: flex;
      align-items: center;
    }
  }
  .table-operator {
    .operate-item {
      display: inline-block;
      font-size: 14px;
      padding: 0 4px;
      cursor: pointer;
    }
    .operate-minus {
      color: #f53f3f;
    }
    .operate-plus {
      color: #165dff;
    }
  }
  .business-fee-table {
    width: 100%;
    height: 400px;
  }
  .operate-list {
    padding-bottom: 10px;
  }
  .num {
    color: #1890ff;
  }
  .mr56 {
    margin-right: 56px;
  }
</style>
